package com.hotlcc.bark.common.bean;

import com.hotlcc.bark.common.exception.BusinessException;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import java.io.Serializable;

@ToString(callSuper = true)
@Getter
@Slf4j
public class RestResult implements Serializable {
    private static final long serialVersionUID = -3617769769246976345L;

    public static final int SUCCESS_CODE = HttpStatus.OK.value();
    public static final int DEFAULT_ERROR_CODE = HttpStatus.BAD_REQUEST.value();

    private static final String SUCCESS_MESSAGE = "success";

    private int code = SUCCESS_CODE;
    private String message = SUCCESS_MESSAGE;
    private Object data;
    private long timestamp = System.currentTimeMillis() / 1000;

    private static RestResult build(int code, String message, Object data) {
        RestResult result = new RestResult();
        result.code = code;
        result.message = message;
        result.data = data;
        return result;
    }

    public static RestResult success(String message, Object data) {
        return build(SUCCESS_CODE, message, data);
    }

    public static RestResult success(Object data) {
        return success(SUCCESS_MESSAGE, data);
    }

    public static RestResult success() {
        return success(null);
    }

    public static RestResult error(int code, String message) {
        return build(code, message, null);
    }

    public static RestResult error(String message) {
        return error(DEFAULT_ERROR_CODE, message);
    }

    public static RestResult error(Exception e) {
        return error(e.getMessage());
    }

    public static RestResult error(BusinessException e) {
        return error(e.getCode(), e.getMessage());
    }

    public static RestResult error(HttpStatus status) {
        return error(status.value(), status.getReasonPhrase());
    }
}
